package com.deyang.util;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;

import java.io.File;

/**
 * 项目文件工具类
 */
public class ProjectFileUtil {

    private static final String TAG = "ProjectFileUtil";

    /**
     * 安装打开 文件
     *
     * @param activity
     * @param filePath
     */
    public static void install(Activity activity, String filePath) {
        Logger.i(TAG, "开始执行安装: " + filePath);
        File apkFile = new File(filePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Logger.e(TAG, "版本大于 N ，开始使用 fileProvider 进行安装");
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(
                    activity
                    , "com.runsheng.intopieces.fileprovider"
                    , apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            Logger.e(TAG, "正常进行安装");
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        activity.startActivity(intent);
    }


    /**
     * 获取versionCode和versionName 这两个参数是写在manifest.xml文件中
     */
    public static String getVersionName(Activity activity) {
        int versioncode;
        String versionname = null;
        PackageManager pm = activity.getPackageManager();
        try {
            PackageInfo packageInfo = pm.getPackageInfo(activity.getPackageName(), 0);
            versioncode = packageInfo.versionCode;
            versionname = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionname;
    }
}
